package com.cat2bug.junit.service.report;

import com.cat2bug.junit.service.IReport;
import com.cat2bug.junit.util.AppUtils;
import freemarker.cache.ClassTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.logging.log4j.util.Strings;

import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 抽象Html报告
 */
public abstract class AbstractHtmlReport implements IReport {
    private final static String COMPILE_PATH = "target/cat2bug-junit/report";

    private final static String TEMPLATE_PATH = "/templates";

    protected abstract String getTemplateName();

    protected abstract String getOutputFileName();

    protected abstract Map getData();

    protected abstract String getReport(String htmlFile);

    @Override
    public Object getReport() {
        StringBuffer sb = new StringBuffer();
        try{
            Configuration configuration = new Configuration(Configuration.VERSION_2_3_30);
            // 使用类路径下的模板加载器
            ClassTemplateLoader templateLoader = new ClassTemplateLoader(getClass(), TEMPLATE_PATH);
            configuration.setTemplateLoader(templateLoader);
            configuration.setDefaultEncoding("utf-8");
            Template template = configuration.getTemplate(this.getTemplateName());

            Map dataModel = this.getData();
            File dir =new File(COMPILE_PATH);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            File file = new File(dir, this.getOutputFileName());
            Writer out = new FileWriter(file,false);
            template.process(dataModel, out);
            String report = this.getReport(file.getAbsolutePath());
            if(Strings.isNotBlank(report)){
                sb.append(report);
            }
            out.close();
        }catch (Exception e){
            e.printStackTrace();
        }

        if(sb.length()>0) {
            return sb.toString();
        }
        return null;
    }
}
